<template>
  <div class="document-edit-tools">
    <el-form :model="configData" label-width="80px">
      <div class="form-row">
        <el-form-item label="文档名称" prop="name" required style="flex: 1; margin-right: 20px">
          <el-input v-model="configData.name" placeholder="请输入配置名称" clearable />
        </el-form-item>

        <el-form-item label="文档类型" style="flex: 1; margin-right: 20px">
          <el-select v-model="configData.type" placeholder="请选择文档类型" style="width: 100%">
            <el-option label="智能体" value="quickTools" />
            <el-option label="MCP" value="MCPTools" />
            <el-option label="工作流" value="workflowComponents" />
          </el-select>
        </el-form-item>

        <el-form-item label="关联工具" style="flex: 1">
          <el-select v-model="localSelectedTools" multiple filterable placeholder="请选择关联工具" style="width: 100%"
            :loading="loadingTools" @focus="loadTools">
            <el-option-group v-for="(tools, category) in toolList" :key="category" :label="getCategoryLabel(category)">
              <el-option v-for="tool in tools" :key="tool.id" :label="tool.name" :value="tool.id">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <span>{{ tool.name }}</span>
                  <span v-if="tool.description" style="font-size: 12px; color: #999; margin-left: 10px; max-width: 250px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ tool.description || '' }}</span>
                </div>
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
      </div>

      <!-- 编辑工具按钮区域 -->
      <div class="edit-tools">
        <el-button-group>
          <el-button type="primary" @click="addTitleBlock('h1')" size="small">H1</el-button>
          <el-button type="primary" @click="addTitleBlock('h2')" size="small">H2</el-button>
          <el-button type="primary" @click="addTitleBlock('h3')" size="small">H3</el-button>
          <el-button type="primary" @click="addTitleBlock('h4')" size="small">H4</el-button>
        </el-button-group>

        <el-button type="success" @click="addEmptyParameterBlock" size="small">
          <el-icon>
            <Plus />
          </el-icon>添加参数
        </el-button>

        <el-upload action="#" :auto-upload="false" :on-change="handleImageUpload" :show-file-list="false"
          accept="image/*" class="inline-upload">
          <el-button type="warning" size="small">
            <el-icon>
              <Plus />
            </el-icon>添加图片
          </el-button>
        </el-upload>
      </div>

      <!-- 数据来源设置 -->
      <div class="data-source">
        <el-form-item label="数据来源" style="flex: 1">
          <el-radio-group v-model="configSource" @change="handleConfigSourceChange" size="small">
            <el-radio label="manual">手动输入</el-radio>
            <el-radio label="file">文本文件</el-radio>
            <el-radio label="database">数据库</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 文件上传选项 -->
        <template v-if="configSource === 'file'">
          <el-upload class="config-upload" action="#" :auto-upload="false" :on-change="handleFileChange" :limit="1"
            :file-list="fileList">
            <el-button type="primary" size="small">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">请上传文本文件</div>
            </template>
          </el-upload>
          <el-button type="success" @click="loadConfigData" :loading="isLoading" size="small">
            加载数据
          </el-button>
        </template>

        <!-- 数据库配置选项 -->
        <template v-if="configSource === 'database'">
          <div class="db-config-form">
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="数据库类型" label-width="80px">
                  <el-select v-model="dbConfig.type" placeholder="选择类型" size="small">
                    <el-option label="MySQL" value="mysql" />
                    <el-option label="PostgreSQL" value="postgresql" />
                    <el-option label="SQLite" value="sqlite" />
                    <el-option label="MongoDB" value="mongodb" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="主机地址" label-width="80px">
                  <el-input v-model="dbConfig.host" placeholder="主机地址" size="small" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="数据库名" label-width="80px">
                  <el-input v-model="dbConfig.database" placeholder="数据库" size="small" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="8">
                <el-form-item label="表名" label-width="80px">
                  <el-input v-model="dbConfig.table" placeholder="表名" size="small" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="用户名" label-width="80px">
                  <el-input v-model="dbConfig.username" placeholder="用户名" size="small" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="密码" label-width="80px">
                  <el-input v-model="dbConfig.password" type="password" placeholder="密码" size="small" show-password />
                </el-form-item>
              </el-col>
            </el-row>
            <el-button type="success" @click="loadConfigData" :loading="isLoading" size="small">
              <el-icon>
                <Download />
              </el-icon>加载数据
            </el-button>
          </div>
        </template>
      </div>

      <!-- 内容区域 -->
      <div class="content-blocks">
        <el-empty v-if="parameterBlocks.length === 0 && documentBlocks.length === 0 && imageBlocks.length === 0"
          description="暂无内容，请使用上方按钮添加内容" />

        <div v-else class="blocks-list">
          <!-- 按创建时间排序的所有区块进行编辑 -->
          <div v-for="(block, index) in orderedBlocksForEdit" :key="index" class="block-item">
            <!-- 文档块 -->
            <template v-if="block.blockType === 'document'">
              <div class="document-item">
                <div class="document-item-header">
                  <el-tag :type="getTagType(block.type)" size="small">{{ block.type.toUpperCase() }}</el-tag>
                  <el-input v-model="localDocumentBlocks[getOriginalIndex('document', index)].title" placeholder="输入标题"
                    class="document-title-input"
                    @input="updateDocTitle(index, localDocumentBlocks[getOriginalIndex('document', index)].title)" />
                  <el-button type="danger" @click="removeBlock(block.blockType, index)" size="small" circle>
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </div>
                <el-input v-model="localDocumentBlocks[getOriginalIndex('document', index)].content" type="textarea"
                  :rows="block.rows" placeholder="请输入内容"
                  @input="adjustTextareaHeight(localDocumentBlocks[getOriginalIndex('document', index)])"
                  class="document-content-input" />
              </div>
            </template>

            <!-- 参数块 -->
            <template v-else-if="block.blockType === 'parameter'">
              <div class="parameter-item">
                <el-input v-model="localParameterBlocks[getOriginalIndex('parameter', index)].key" placeholder="参数名"
                  style="width: 30%" size="small"
                  @input="updateParameterName(index, localParameterBlocks[getOriginalIndex('parameter', index)].key)" />
                <el-input v-model="localParameterBlocks[getOriginalIndex('parameter', index)].value" placeholder="参数值"
                  style="width: 60%; margin: 0 10px" size="small"
                  @input="updateParameterValue(index, localParameterBlocks[getOriginalIndex('parameter', index)].value)" />
                <el-button type="danger" @click="removeBlock(block.blockType, index)" size="small" circle>
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-button>
              </div>
            </template>

            <!-- 图片块 -->
            <template v-else-if="block.blockType === 'image'">
              <div class="image-item">
                <el-image :src="block.url" :preview-src-list="[block.url]" fit="cover" class="image-thumbnail" />
                <div class="image-actions">
                  <el-input v-model="localImageBlocks[getOriginalIndex('image', index)].name" placeholder="图片名称"
                    size="small" class="image-name-input"
                    @input="updateImageName(index, localImageBlocks[getOriginalIndex('image', index)].name)" />
                  <el-button type="danger" @click="removeBlock(block.blockType, index)" size="small" circle>
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, defineProps, defineEmits } from 'vue';
import { Plus, Download, Delete } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import type { UploadFile, UploadUserFile } from 'element-plus';
import { universalDocService, ConfigItem } from '@/services/universalDocService';

interface DocumentBlock {
  type: string;
  title: string;
  content: string;
  rows: number;
  createdAt: number;
}

interface ParameterBlock {
  key: string;
  value: string;
  createdAt: number;
}

interface ImageBlock {
  url: string;
  name: string;
  createdAt: number;
}

// 定义合并后的区块类型
type DocumentBlockWithType = DocumentBlock & { blockType: 'document' };
type ParameterBlockWithType = ParameterBlock & { blockType: 'parameter' };
type ImageBlockWithType = ImageBlock & { blockType: 'image' };
type CombinedBlock = DocumentBlockWithType | ParameterBlockWithType | ImageBlockWithType;

interface DbConfig {
  type: string;
  host: string;
  database: string;
  table: string;
  username: string;
  password: string;
}

interface ToolItem {
  id: string;
  name: string;
  description: string;
}

interface ToolCategory {
  quickTools: ToolItem[];
  MCPTools: ToolItem[];
  workflowComponents: ToolItem[];
}

const props = defineProps({
  configData: {
    type: Object as () => ConfigItem,
    required: true
  },
  parameterBlocks: {
    type: Array as () => ParameterBlock[],
    required: true
  },
  documentBlocks: {
    type: Array as () => DocumentBlock[],
    required: true
  },
  imageBlocks: {
    type: Array as () => ImageBlock[],
    required: true
  },
  selectedTools: {
    type: Array as () => string[],
    default: () => []
  }
});

const emit = defineEmits([
  'update:configData',
  'update:parameterBlocks',
  'update:documentBlocks',
  'update:imageBlocks',
  'update:selectedTools',
  'compiled-content-updated'
]);

// Configuration source
const configSource = ref('manual');
const fileList = ref<UploadUserFile[]>([]);
const isLoading = ref(false);

// Database configuration
const dbConfig = ref<DbConfig>({
  type: 'mysql',
  host: '',
  database: '',
  table: '',
  username: '',
  password: ''
});

// Tools
const toolList = ref<ToolCategory>({
  quickTools: [],
  MCPTools: [],
  workflowComponents: []
});
const localSelectedTools = ref<string[]>([]);
const loadingTools = ref(false);

// 创建本地响应式引用
const localDocumentBlocks = ref<DocumentBlock[]>([]);
const localParameterBlocks = ref<ParameterBlock[]>([]);
const localImageBlocks = ref<ImageBlock[]>([]);

// 监听属性变化
watch(() => props.documentBlocks, (newVal) => {
  localDocumentBlocks.value = JSON.parse(JSON.stringify(newVal));
}, { immediate: true, deep: true });

watch(() => props.parameterBlocks, (newVal) => {
  localParameterBlocks.value = JSON.parse(JSON.stringify(newVal));
}, { immediate: true, deep: true });

watch(() => props.imageBlocks, (newVal) => {
  localImageBlocks.value = JSON.parse(JSON.stringify(newVal));
}, { immediate: true, deep: true });

// 提取一个用于比较两个数组是否相等的辅助函数
const areArraysEqual = (arr1: any[], arr2: any[]): boolean => {
  if (arr1.length !== arr2.length) return false;
  return JSON.stringify(arr1.sort()) === JSON.stringify(arr2.sort());
};

// 监听 configData 的 agent_ids 变化
watch(() => props.configData.agent_ids, (newVal, oldVal) => {
  if (!newVal && localSelectedTools.value.length > 0) {
    // 如果 agent_ids 变为空但本地选择不为空，则清空本地选择
    localSelectedTools.value = [];
  } else if (newVal && !areArraysEqual(newVal, localSelectedTools.value)) {
    // 如果 agent_ids 有值且与本地选择不同，则更新本地选择
    localSelectedTools.value = [...newVal];
  }
}, { immediate: true });

// 监听 props.selectedTools 的变化
watch(() => props.selectedTools, (newVal, oldVal) => {
  if (newVal && !areArraysEqual(newVal, localSelectedTools.value)) {
    localSelectedTools.value = [...newVal];
  }
}, { immediate: true });

// 监听本地数据变化
watch(localDocumentBlocks, (newVal) => {
  if (JSON.stringify(newVal) !== JSON.stringify(props.documentBlocks)) {
    emit('update:documentBlocks', newVal);
  }
}, { deep: true });

watch(localParameterBlocks, (newVal) => {
  if (JSON.stringify(newVal) !== JSON.stringify(props.parameterBlocks)) {
    emit('update:parameterBlocks', newVal);
  }
}, { deep: true });

watch(localImageBlocks, (newVal) => {
  if (JSON.stringify(newVal) !== JSON.stringify(props.imageBlocks)) {
    emit('update:imageBlocks', newVal);
  }
}, { deep: true });

// 监听 localSelectedTools 的变化
watch(localSelectedTools, (newVal, oldVal) => {
  const configNeedsUpdate = props.configData.agent_ids && !areArraysEqual(newVal, props.configData.agent_ids);
  const propsNeedUpdate = !areArraysEqual(newVal, props.selectedTools);
  
  if (configNeedsUpdate) {
    emit('update:configData', {
      ...props.configData,
      agent_ids: [...newVal]
    });
  }
  
  if (propsNeedUpdate) {
    emit('update:selectedTools', [...newVal]);
  }
}, { deep: true });

// 按创建时间排序的所有区块，用于编辑视图
const orderedBlocksForEdit = computed<CombinedBlock[]>({
  get: () => {
    const allBlocks: CombinedBlock[] = [
      ...props.documentBlocks.map(block => ({
        ...block,
        blockType: 'document' as const
      })),
      ...props.parameterBlocks.map(block => ({
        ...block,
        blockType: 'parameter' as const
      })),
      ...props.imageBlocks.map(block => ({
        ...block,
        blockType: 'image' as const
      }))
    ];

    return allBlocks.sort((a, b) => a.createdAt - b.createdAt);
  },
  set: (newValue: CombinedBlock[]) => {
    // 当修改排序后的区块时，更新原始数组
    const docBlocks: DocumentBlock[] = [];
    const paramBlocks: ParameterBlock[] = [];
    const imgBlocks: ImageBlock[] = [];

    newValue.forEach(block => {
      if (block.blockType === 'document') {
        const { blockType, ...docBlock } = block;
        docBlocks.push(docBlock as DocumentBlock);
      } else if (block.blockType === 'parameter') {
        const { blockType, ...paramBlock } = block;
        paramBlocks.push(paramBlock as ParameterBlock);
      } else if (block.blockType === 'image') {
        const { blockType, ...imgBlock } = block;
        imgBlocks.push(imgBlock as ImageBlock);
      }
    });

    emit('update:documentBlocks', docBlocks);
    emit('update:parameterBlocks', paramBlocks);
    emit('update:imageBlocks', imgBlocks);
  }
});

// 处理配置源变更
const handleConfigSourceChange = (value: string) => {
  if (value === 'manual') {
    // 无需额外操作
  } else if (value === 'file') {
    fileList.value = [];
  } else if (value === 'database') {
    // 重置数据库配置
    dbConfig.value = {
      type: 'mysql',
      host: '',
      database: '',
      table: '',
      username: '',
      password: ''
    };
  }
};

// 处理文件变更
const handleFileChange = (uploadFile: UploadFile) => {
  fileList.value = [uploadFile];
};

// 加载配置数据
const loadConfigData = async () => {
  isLoading.value = true;

  try {
    if (configSource.value === 'file') {
      if (fileList.value.length === 0) {
        ElMessage.warning('请先选择文件');
        isLoading.value = false;
        return;
      }

      const file = fileList.value[0].raw;
      if (!file) {
        ElMessage.warning('无法读取文件');
        isLoading.value = false;
        return;
      }

      const reader = new FileReader();
      reader.onload = (e) => {
        if (e.target) {
          try {
            const content = e.target.result as string;

            // 尝试检测是否为HTML内容
            if (content.trim().startsWith('<') && content.includes('</')) {
              // 可能是HTML内容，直接设置到编辑器
              props.configData.htmlContent = content;
              props.configData.content = content;
            } else {
              // 普通文本，转换为HTML格式
              const htmlContent = `<p>${content.replace(/\n/g, '</p><p>')}</p>`;
              props.configData.htmlContent = htmlContent;
              props.configData.content = content;
            }

            ElMessage.success('文件内容已加载');
          } catch (error) {
            ElMessage.error('文件内容解析失败');
            console.error(error);
          }
          isLoading.value = false;
        }
      };
      reader.onerror = () => {
        ElMessage.error('读取文件失败');
        isLoading.value = false;
      };
      reader.readAsText(file);

    } else if (configSource.value === 'database') {
      // 这里模拟从后端API加载数据
      // 实际项目中应该调用后端API获取数据

      // 检查必填字段
      if (!dbConfig.value.host || !dbConfig.value.database || !dbConfig.value.table) {
        ElMessage.warning('请填写必要的数据库连接信息');
        isLoading.value = false;
        return;
      }

      // 模拟API请求延迟
      setTimeout(() => {
        // 模拟数据内容
        const sampleData = {
          type: dbConfig.value.type,
          connection: {
            host: dbConfig.value.host,
            database: dbConfig.value.database,
            user: dbConfig.value.username,
          },
          table: dbConfig.value.table,
          sample_data: [
            { id: 1, name: "示例数据1", value: 100 },
            { id: 2, name: "示例数据2", value: 200 },
            { id: 3, name: "示例数据3", value: 300 },
          ]
        };

        // 将JSON数据转换为HTML表格
        const tableHtml = generateTableFromData(sampleData.sample_data);
        props.configData.htmlContent = tableHtml;
        props.configData.content = JSON.stringify(sampleData, null, 2);

        ElMessage.success('数据库配置已加载');
        isLoading.value = false;
      }, 1000);
    }
  } catch (error) {
    console.error('加载数据出错：', error);
    ElMessage.error('加载数据失败');
    isLoading.value = false;
  }
};

// 将数据转换为HTML表格
const generateTableFromData = (data: any[]) => {
  if (!data || !data.length) return '<p>无数据</p>';

  // 获取所有列名
  const columns = Object.keys(data[0]);

  let tableHtml = '<table border="1" style="width:100%; border-collapse: collapse;">';

  // 表头
  tableHtml += '<thead><tr>';
  columns.forEach(col => {
    tableHtml += `<th style="padding: 8px; text-align: left; background-color: #f2f2f2;">${col}</th>`;
  });
  tableHtml += '</tr></thead>';

  // 表格内容
  tableHtml += '<tbody>';
  data.forEach(row => {
    tableHtml += '<tr>';
    columns.forEach(col => {
      tableHtml += `<td style="padding: 8px; border: 1px solid #ddd;">${row[col]}</td>`;
    });
    tableHtml += '</tr>';
  });
  tableHtml += '</tbody></table>';

  return tableHtml;
};

// 添加空参数块
const addEmptyParameterBlock = () => {
  const newBlock = {
    key: '新参数',
    value: '请输入参数值',
    createdAt: Date.now()
  };
  const updatedBlocks = [...props.parameterBlocks, newBlock];
  emit('update:parameterBlocks', updatedBlocks);
};

// 获取标签类型
const getTagType = (type: string): string => {
  const typeMap: Record<string, string> = {
    h1: 'primary',
    h2: 'success',
    h3: 'warning',
    h4: 'danger'
  };
  return typeMap[type] || 'info';
};

// 添加标题块
const addTitleBlock = (type: string) => {
  const titleMap: Record<string, string> = {
    h1: '一级标题',
    h2: '二级标题',
    h3: '三级标题',
    h4: '四级标题'
  };

  const newBlock = {
    type,
    title: titleMap[type],
    content: '请输入内容',
    rows: 3,
    createdAt: Date.now()
  };
  const updatedBlocks = [...props.documentBlocks, newBlock];
  emit('update:documentBlocks', updatedBlocks);
};

// 调整文本区域高度
const adjustTextareaHeight = (block: DocumentBlock) => {
  const lineCount = block.content.split('\n').length;
  block.rows = Math.max(3, Math.min(10, lineCount + 1));
};

// 处理图片上传
const handleImageUpload = (file: UploadFile) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    if (e.target?.result) {
      const newBlock = {
        url: e.target.result as string,
        name: file.name,
        createdAt: Date.now()
      };
      const updatedBlocks = [...props.imageBlocks, newBlock];
      emit('update:imageBlocks', updatedBlocks);
      ElMessage.success('图片上传成功');
    }
  };
  reader.readAsDataURL(file.raw as Blob);
  return false; // 阻止默认上传行为
};

// 移除区块
const removeBlock = (blockType: string, index: number) => {
  if (blockType === 'document') {
    const newDocumentBlocks = [...props.documentBlocks];
    newDocumentBlocks.splice(index, 1);
    emit('update:documentBlocks', newDocumentBlocks);
  } else if (blockType === 'parameter') {
    const newParameterBlocks = [...props.parameterBlocks];
    newParameterBlocks.splice(index, 1);
    emit('update:parameterBlocks', newParameterBlocks);
  } else if (blockType === 'image') {
    const newImageBlocks = [...props.imageBlocks];
    newImageBlocks.splice(index, 1);
    emit('update:imageBlocks', newImageBlocks);
  }
};

// 加载工具列表
const loadTools = async () => {
  try {
    loadingTools.value = true;
    // 从智能体API加载工具列表
    const agentTools = await universalDocService.getAgentTools();
    
    console.log('API返回的工具列表:', agentTools);
 
    // 根据当前选择的文档类型过滤工具
    const currentType = props.configData.type;
    
    // 构建新的工具列表，直接使用API返回的结构
    const newToolList = {
      quickTools: currentType === 'quickTools' ? agentTools.quickTools || [] : [],
      MCPTools: currentType === 'MCPTools' ? agentTools.MCPTools || [] : [],
      workflowComponents: currentType === 'workflowComponents' ? agentTools.workflowComponents || [] : []
    };
    
    console.log('过滤后的工具列表:', newToolList);
    
    // 更新工具列表
    toolList.value = newToolList;

    // 确保已选中的工具在列表中
    const allTools = [
      ...newToolList.quickTools,
      ...newToolList.MCPTools,
      ...newToolList.workflowComponents
    ];
    
    console.log('所有可选工具:', allTools);
    
    // 存储当前选中的工具ID
    const currentSelectedTools = [...localSelectedTools.value];
    console.log('当前选中的工具:', currentSelectedTools);
    
    // 过滤掉不在当前工具列表中的已选工具
    const filteredTools = currentSelectedTools.filter(id => 
      allTools.some(tool => tool.id === id)
    );
    
    console.log('过滤后的选中工具:', filteredTools);
    
    // 只有当工具列表确实发生变化时才更新
    if (JSON.stringify(filteredTools) !== JSON.stringify(localSelectedTools.value)) {
      localSelectedTools.value = filteredTools;
    }
  } catch (error) {
    console.error('加载智能体工具失败:', error);
    ElMessage.error('加载智能体工具失败');
  } finally {
    loadingTools.value = false;
  }
};

// 更新编译内容的功能
const updateCompiledContent = () => {
  // 合并所有区块并按创建时间排序
  const allBlocks = [
    ...props.parameterBlocks.map(p => ({ ...p, type: 'parameter' })),
    ...props.documentBlocks.map(d => ({ ...d, type: 'document' })),
    ...props.imageBlocks.map(i => ({ ...i, type: 'image' }))
  ].sort((a, b) => a.createdAt - b.createdAt);

  let content = '';

  // 按照创建时间顺序处理每个块，每个块都是独立的，不再按类型分组
  allBlocks.forEach(block => {
    // 添加区块内容
    if ('key' in block && 'value' in block) {
      // 参数块
      content += `#### ${block.key}\n${block.value}\n\n`;
    } else if ('title' in block && 'content' in block) {
      // 文档块
      content += `### ${block.title}\n${block.content}\n\n`;
    } else if ('url' in block && 'name' in block) {
      // 图片块
      content += `#### ${block.name}\n![${block.name}](${block.url})\n\n`;
    }
  });

  // 只有当内容确实发生变化时才更新
  if (content !== props.configData.compiledContent) {
    const updatedConfig = { ...props.configData, compiledContent: content };
    emit('update:configData', updatedConfig);
    emit('compiled-content-updated', content);
  }
};

// 监听相关数据变化，自动更新编译区块内容，减少监听次数
watch(
  [() => props.parameterBlocks, () => props.documentBlocks, () => props.imageBlocks],
  () => {
    // 添加节流，减少频繁更新
    updateCompiledContent();
  },
  { deep: true, flush: 'post' } // 使用post确保在渲染后更新
);

// Helper function to get original index
const getOriginalIndex = (type: string, combinedIndex: number): number => {
  // 获取在当前排序后的数组中，给定索引的元素
  const sortedBlocks = orderedBlocksForEdit.value;
  if (combinedIndex >= sortedBlocks.length) {
    return 0; // 防止越界
  }

  const targetBlock = sortedBlocks[combinedIndex];

  // 根据块类型决定在哪个原始数组中查找
  if (type === 'document') {
    const documentIndex = props.documentBlocks.findIndex(
      block => block.createdAt === targetBlock.createdAt
    );
    return documentIndex >= 0 ? documentIndex : 0;
  }
  else if (type === 'parameter') {
    const parameterIndex = props.parameterBlocks.findIndex(
      block => block.createdAt === targetBlock.createdAt
    );
    return parameterIndex >= 0 ? parameterIndex : 0;
  }
  else if (type === 'image') {
    const imageIndex = props.imageBlocks.findIndex(
      block => block.createdAt === targetBlock.createdAt
    );
    return imageIndex >= 0 ? imageIndex : 0;
  }

  return 0;
};

// Update document title
const updateDocTitle = (index: number, newTitle: string) => {
  const originalIndex = getOriginalIndex('document', index);
  emit('update:documentBlocks', [
    ...props.documentBlocks.slice(0, originalIndex),
    { ...props.documentBlocks[originalIndex], title: newTitle },
    ...props.documentBlocks.slice(originalIndex + 1)
  ]);
};

// Update parameter name
const updateParameterName = (index: number, newName: string) => {
  const originalIndex = getOriginalIndex('parameter', index);
  emit('update:parameterBlocks', [
    ...props.parameterBlocks.slice(0, originalIndex),
    { ...props.parameterBlocks[originalIndex], key: newName },
    ...props.parameterBlocks.slice(originalIndex + 1)
  ]);
};

// Update image name
const updateImageName = (index: number, newName: string) => {
  const originalIndex = getOriginalIndex('image', index);
  emit('update:imageBlocks', [
    ...props.imageBlocks.slice(0, originalIndex),
    { ...props.imageBlocks[originalIndex], name: newName },
    ...props.imageBlocks.slice(originalIndex + 1)
  ]);
};

// Update parameter value
const updateParameterValue = (index: number, newValue: string) => {
  const originalIndex = getOriginalIndex('parameter', index);
  emit('update:parameterBlocks', [
    ...props.parameterBlocks.slice(0, originalIndex),
    { ...props.parameterBlocks[originalIndex], value: newValue },
    ...props.parameterBlocks.slice(originalIndex + 1)
  ]);
};

// 在 script setup 部分修改
const getCategoryLabel = (category: string): string => {
  const labelMap: Record<string, string> = {
    quickTools: '智能体工具',
    MCPTools: 'MCP组件',
    workflowComponents: '工作流组件'
  };
  return labelMap[category] || category;
};

// 监听文档类型变化，自动加载对应类型的工具
watch(() => props.configData.type, (newType, oldType) => {
  if (newType && newType !== oldType) {
    loadTools();
  }
}, { immediate: true });
</script>

<style scoped>
.document-edit-tools {
  width: 100%;
  height: 100%;
  overflow-y: auto;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-row .el-form-item {
  margin-bottom: 0;
  flex: 1;
}

.edit-tools {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.data-source {
  margin-bottom: 15px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.content-blocks {
  margin-top: 20px;
}

.blocks-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.block-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  background: #fff;
  transition: all 0.3s ease;
}

.block-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.document-item {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.document-item-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.document-title-input {
  flex: 1;
}

.document-content-input {
  width: 100%;
}

.parameter-item {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  padding: 10px;
}

.image-thumbnail {
  max-width: 200px;
  max-height: 200px;
  object-fit: contain;
  border-radius: 4px;
}

.image-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.image-name {
  font-size: 12px;
  color: #606266;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-name-input {
  width: 70%;
}

.inline-upload {
  display: inline-block;
}

.db-config-form {
  margin-top: 15px;
}

.config-upload {
  margin: 10px 0;
}

.el-upload__tip {
  line-height: 1.2;
  margin-top: 4px;
  color: #64748b;
}
</style>